package com.example.casper.Experiment2024.share;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.gone.SharedViewModel;
import com.example.casper.Experiment2024.items.locationSave;
import com.example.casper.Experiment2024.share.LocationAdapter;
import com.example.casper.Experiment2024.items.Location;

import java.util.ArrayList;
import java.util.List;

public class ShareFragment extends Fragment {

    private RecyclerView recyclerView;
    private LocationAdapter locationAdapter;
    private List<Location> locationList;
    private SharedViewModel sharedViewModel;

    public static ShareFragment newInstance() {
        ShareFragment fragment = new ShareFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationList = new ArrayList<>();
        locationSave databank = new locationSave(requireActivity());
        locationList = databank.readShareItems();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_share, container, false);

        recyclerView = view.findViewById(R.id.recyclerView_locations);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        locationAdapter = new LocationAdapter(requireActivity(), locationList);
        recyclerView.setAdapter(locationAdapter);

        // Initialize the ViewModel here
        // 获取 SharedViewModel 的实例
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
//        sharedViewModel.getLocationUpdated().observe(getViewLifecycleOwner(), this::updateLocation);
        sharedViewModel.getLocationUpdated().observe(getViewLifecycleOwner(), location -> {
            if (location != null) {
                // 检查是否已经存在该位置，避免重复添加
                if (!locationList.contains(location)) {
                    locationList.add(location);
                    locationAdapter.notifyItemInserted(locationList.size() - 1); // 刷新 RecyclerView
                    Toast.makeText(getContext(), "Location added to shared list", Toast.LENGTH_SHORT).show();
                }
            }
        });
        Log.d("ViewModel", "Fragment ViewModel: " + new ViewModelProvider(requireActivity()).get(SharedViewModel.class).toString());
        // 从持久化存储中加载已分享的位置
        loadSharedLocations();


        return view;
    }
    @Override
    public void onResume() {
        super.onResume();

        // 检查数据是否有变化
        checkDataChangesAndReload();
    }

    private void checkDataChangesAndReload() {
        // 获取当前存储的数据（从 databank 加载）
        locationSave locationDataManager = new locationSave(requireContext());
        List<Location> newLocations = locationDataManager.readShareItems(); // 从存储读取的最新数据

        // 如果数据有变化（即新数据与现有数据不同），则重新加载 RecyclerView
        if (newLocations != null && !newLocations.equals(locationList)) {
            // 数据有变化，更新 RecyclerView
            locationList.clear();
            locationList.addAll(newLocations);
            locationAdapter.notifyDataSetChanged(); // 通知适配器刷新页面
            Log.d("ShareFragment", "Data changed. RecyclerView reloaded.");
        } else {
            Log.d("ShareFragment", "No changes in data.");
        }
    }

    private void updateLocation(Location location) {
        locationList.add(location);
        locationAdapter.notifyItemInserted(locationList.size() - 1);
        Toast.makeText(getContext(), "Location added to shared list", Toast.LENGTH_SHORT).show();
    }

    private void loadSharedLocations() {
        // 创建 locationSave 实例
        locationSave locationDataManager = new locationSave(requireContext());

        // 从持久化存储中读取已分享的位置
        List<Location> savedLocations = locationDataManager.readShareItems();

        // 更新 RecyclerView 数据
        if (savedLocations != null && !savedLocations.isEmpty()) {
            locationList.clear();
            locationList.addAll(savedLocations);
            locationAdapter.notifyDataSetChanged(); // 通知适配器刷新 RecyclerView
        }
    }

}